package tests;

import common.IP;
import common.Utils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.IOException;
import java.time.Duration;

public class SignIn extends Utils {
    public static String url = "http://" + IP.ip + "/login.html";

    public SignIn() {
        super(url);
    }

    //封装弹窗方法
    public void waitAlert(WebDriver driver){
        //显式等待弹窗的出现
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
        Alert alert = null;
        try {
            //检测弹窗的存在，存在会显式返回一个有效的alert对象
            alert = wait.until(ExpectedConditions.alertIsPresent());
            alert.accept();
        }catch (Exception e){
            System.out.println("SignInFail");
        }
    }

    /**
     * 登录失败
     */
    public void fail() {
        //通过刷新清空输入框
        driver.navigate().refresh();

        //1.用户名和密码未输入
        driver.findElement(By.cssSelector("#submit")).click();
        waitAlert(driver);

        //2.输入用户名不输入密码
        driver.findElement(By.cssSelector("#username")).sendKeys("zhangsan");
        driver.findElement(By.cssSelector("#submit")).click();
        waitAlert(driver);

        //3.输入密码不输入用户名
        driver.navigate().refresh();
        driver.findElement(By.cssSelector("#password")).sendKeys("123");
        driver.findElement(By.cssSelector("#submit")).click();
        waitAlert(driver);

        //4.输入的用户名和密码错误
        driver.navigate().refresh();
        driver.findElement(By.cssSelector("#username")).sendKeys("zhangsand");
        driver.findElement(By.cssSelector("#password")).sendKeys("123456d");
        driver.findElement(By.cssSelector("#submit")).click();
        waitAlert(driver);
        driver.navigate().refresh();
    }

    /**
     * 登录成功
     */
    public void success() throws IOException {
        //删除所有cookie
        driver.manage().deleteAllCookies();
        driver.findElement( By.cssSelector("#username")).sendKeys("zhangsan");
        driver.findElement(By.cssSelector("#password")).sendKeys("123");
        driver.findElement(By.cssSelector("#submit")).click();
        waitAlert(driver);
        //登录成功后页面跳转，判断页面元素是否存在
        String txt = driver.findElement(By.cssSelector("#match-button")).getText();
        assert txt.equals("开始匹配");
        //获取页面标题
        String title = driver.getTitle();
        //字符串断言
        assert title.equals("游戏大厅");
        System.out.println(title);
    }
}
